package camuyen.ltwlibrary.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import camuyen.ltwlibrary.dao.UserDao;
import camuyen.ltwlibrary.model.User;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = request.getParameter("username").toLowerCase();
		String password = request.getParameter("password");
		String rePassword = request.getParameter("rePassword");
		System.out.println(username +" and "+password + " " + rePassword);
		
		boolean isExisted = UserDao.exists(username);
		boolean isPasswordMatch = password.equals(rePassword);
		
		if (!isPasswordMatch) {
			session.setAttribute("messagePasswordIsNotMatch", "Password is not match.");
		}
		
		if (isExisted){
			session.setAttribute("messageUsernameExists", "This username is existed.");
			session.setAttribute("username", username);
		}
		
		if (!isExisted && isPasswordMatch) {
			User newUser = new User();
			newUser.setUsername(username);
			newUser.setPassword(password);
			UserDao.saveUser(newUser);
			response.sendRedirect("registerSuccess.jsp");
		} else {
			response.sendRedirect("register.jsp");
		}
	}

}
